package cn.tq365.action.sys;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings({ "serial", "rawtypes" })
public abstract class BaseAction extends ActionSupport implements ModelDriven,
		Preparable {

	/**
	 * 获得HttpServletResponse对象
	 */
	public HttpServletResponse getHttpServletResponse() {
		HttpServletResponse response = (HttpServletResponse) ActionContext
				.getContext().get(ServletActionContext.HTTP_RESPONSE);
		return response;
	}

	/**
	 * 获得HttpServletRequest对象
	 * 
	 * @return
	 */
	public HttpServletRequest getHttpServletRequest() {
		HttpServletRequest request = (HttpServletRequest) ActionContext
				.getContext().get(ServletActionContext.HTTP_REQUEST);
		return request;
	}

	/**
	 * 获取HttpSession对象
	 * 
	 * @return
	 */
	public Map<String, Object> getHttpSession() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		return session;
	}

	/**
	 * 获取Application对象
	 * 
	 * @return
	 */
	public Map<String, Object> getApplication() {
		Map<String, Object> application = ActionContext.getContext()
				.getApplication();
		return application;
	}

	/**
	 * 输出字符串
	 */
	public void print(String str) {
		try {
			PrintWriter out = this.getHttpServletResponse().getWriter();
			out.print(str);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 以JSON格式打印参数信息（调试方法）
	 */
	public void printParamsJSON() {
		// 打印客户端传过来的参数
		JSONObject jsonObject = new JSONObject();
		Map paramMap = this.getHttpServletRequest().getParameterMap();
		jsonObject.putAll(paramMap);
		System.out.println("请求参数：" + jsonObject);
	}

}
